package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Commodity;
import cn.hist.hfp.service.CommodityService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.CommodityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/commodity")
public class CommodityController {

    private final
    CommodityService commodityService;

    private final Authentication authentication;

    @Autowired
    public CommodityController(CommodityService commodityService, Authentication authentication) {
        this.commodityService = commodityService;
        this.authentication = authentication;
    }

    @PostMapping
    public CommodityVO create(@RequestBody Commodity commodity, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return commodityService.create(commodity);
    }

    @GetMapping("/{id}")
    public CommodityVO findOne(@PathVariable int id) {
        MyResponse<Commodity> myResponse = new MyResponse<>();
        return commodityService.findOne(id);
    }

    @GetMapping("/page/{page}")
    public List<CommodityVO> findSome(@RequestParam String type, @RequestParam int producer_id, @PathVariable int page) {
        return commodityService.findSome(type, producer_id, page);
    }

    @GetMapping("/page")
    public int numberOfPages(@RequestParam String type, @RequestParam int producer_id) {
        return commodityService.numberOfPages(type, producer_id);
    }

    @PutMapping
    public CommodityVO update(@RequestBody Commodity commodity) {
        return commodityService.update(commodity);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), commodityService.delete(id));
    }
}
